package com.test.system.admin.service;

import com.test.system.admin.dao.PermDao;
import com.test.system.admin.util.AdminConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.test.system.admin.pojo.Menu;
import com.test.system.admin.dao.MenuDao;

@Service
public class MenuService {

    @Resource
    private MenuDao menuDao;

    public int insert(Menu pojo) {
        return menuDao.insert(pojo);
    }

    public int update(Menu pojo) {
        return menuDao.update(pojo);
    }

    public List<Menu> getMenuList() {
        List<Menu> firstMenu = getFullMenuTree();
        List<Menu> result = new ArrayList<>();
        for (Menu menu : firstMenu) {
            menu.setLevel(1);//一级菜单在页面上的缩进
            result.add(menu);//放当前菜单
            addChildren(menu.getChildren(), result, 2);//放子菜单的菜单
        }
        return result;
    }

    public void addChildren(List<Menu> children, List<Menu> target, int level) {
        for (Menu child : children) {
            child.setLevel(level);
            target.add(child);
            if (child.getChildren().size() > 0) {
                addChildren(child.getChildren(), target, level + 1);
            }
        }
    }

    public List<Menu> getFullMenuTree() {
        List<Menu> menus = menuDao.getMenuList();
        return makeMenuTree(menus, true);
    }

    public List<Menu> makeMenuTree(List<Menu> menus, boolean needButton) {
        List<Menu> firstMenu = new ArrayList<>();//一级菜单
        Map<Integer, Menu> menuMap = new HashMap<>();
        for (Menu menu : menus) {
            if (menu.getParentId() == null) {//一级菜单的父菜单都是空
                firstMenu.add(menu);
            }
            menuMap.put(menu.getId(), menu);
        }
        for (Menu menu : menus) {
            if (!needButton && menu.getType() == AdminConstants.MENU_TYPE_BUTTON) {//如果不需要按钮
                continue;
            }
            if (menu.getParentId() != null) {
                Menu parent = menuMap.get(menu.getParentId());
                if (parent != null) {
                    parent.getChildren().add(menu);
                }
            }
        }
        return firstMenu;
    }

    @Autowired
    private PermDao permDao;

    public List<Menu> getMenuTree(Integer userId) {
        List<Menu> menus = null;
        if (userId == null) {
            menus = menuDao.getMenuList();
        } else {
            menus = permDao.getUserMenu(userId);
        }
        return makeMenuTree(menus, false);
    }

    public List<String> getUserPerms(Integer userId){
        return permDao.getUserPermission(userId);
    }

}
